package com.yehebl.orm.data.mysql;

import com.yehebl.orm.util.LogUtil;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;

/**
 * 表创建或者修改语句-或者获取表列表信息
 * 实际被起用
 */
public class MySqlTableManager {
	
	public static void addColumns(Connection connection, String tableName,String columns) {
		try {
			Statement st = connection.createStatement();
			st.execute("alter table "+tableName+" ADD COLUMN "+columns+" varchar(1000) CHARACTER SET utf8mb4");
//			PreparedStatement prepareStatement = connection.prepareStatement("alter table ? ADD COLUMN ? varchar(1000) CHARACTER SET utf8mb4");
//			prepareStatement.setObject(1, tableName);
//			prepareStatement.setObject(2, columns);
//			prepareStatement.execute();
			connection.close();
		} catch (Exception e) {
			throw new RuntimeException("添加列出错："+e.getMessage());
		}
	}
	
	public static Set<String> getColumns(Connection connection, String tableName) {
		try {
			Set<String> set = new HashSet<>();
			DatabaseMetaData dbmd = connection.getMetaData();
			ResultSet rs = dbmd.getColumns(null, "%", tableName, "%");
			while (rs.next()) {
				set.add(rs.getString("COLUMN_NAME"));
			}
			rs.close();
			connection.close();
			return set;
		} catch (Exception e) {
			LogUtil.printWarn("获取表["+tableName+"]列名信息出错,"+e.getMessage());
			throw new RuntimeException("获取表["+tableName+"]列名信息出错,"+e.getMessage());
		}
	}
}
